package com.assistant.core.modules.sys.adapter;

import com.assistant.exception.AssistantException;
import com.assistant.util.MessageBodyWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.assistant")
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public MessageBodyWrapper<Object> handleException(Exception e) {
        log.error("请求发生异常", e);
        return MessageBodyWrapper.failure("系统异常");
    }

    @ExceptionHandler(AssistantException.class)
    public MessageBodyWrapper<Object> handleException(AssistantException e) {
        log.warn("请求发生异常", e);
        return MessageBodyWrapper.failure(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MessageBodyWrapper<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        log.warn("请求发生异常", e);
        if (fieldErrors.size() > 0) {
            return MessageBodyWrapper.failure(fieldErrors.get(0).getDefaultMessage());
        } else {
            return MessageBodyWrapper.failure("系统异常");
        }
    }

}
